<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      @close="closeDialog"
      @open="open"
    >
      <el-form
        :label-position="labelPosition"
        label-width="1.2rem"
        :model="formLabelAlign"
      >
        <el-form-item label="文件名称：">
          <el-input
            placeholder="请输入文件名称"
            v-model="formLabelAlign.fileName"
            maxlength="200"
          ></el-input>
        </el-form-item>
        <el-form-item label="主题词：">
          <el-input
            placeholder="请输入文件主题词"
            v-model="formLabelAlign.keywords"
            maxlength="200"
          ></el-input>
        </el-form-item>
        <el-form-item label="描述信息:">
          <el-input
            placeholder="请输入描述信息"
            type="textarea"
            v-model="formLabelAlign.memo"
            maxlength="255"
            :autosize="{ minRows: 2 }"
          ></el-input>
        </el-form-item>
        <slot></slot>
        <div class="navUpload">
          <div class="nav">
            <el-form-item label="添加标签:">
              <div class="target-tree-con">
                <div class="input">
                  <tagsGroup
                    :showTagsArr="categoryIds"
                    :tagsClose="true"
                    @tagsDel="tagsDel"
                  ></tagsGroup>
                </div>
                <div class="treeTags block">
                  <el-tree
                    :data="treeTags"
                    node-key="id"
                    show-checkbox
                    default-expand-all
                    :props="defaultProps"
                    @check-change="handleNodeClick"
                    ref="elTree"
                    @check="treeCheck"
                    id="elTree"
                  >
                    <span class="custom-tree-node" slot-scope="{ node }">
                      <span>{{ node.label }}</span>
                    </span>
                  </el-tree>
                </div>
              </div>
            </el-form-item>
          </div>
          <div class="upload">
            <el-form-item label="上传文件：">
              <el-upload
                class="upload-demo"
                :action="baseURL"
                :on-success="handleSuccess"
                :before-upload="beforeUpload"
                :auto-upload="true"
                :data="uploadOtherData"
                :file-list="fileList"
                list-type="text"
                :on-error="handleError"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                accept=".doc,.docx,.pdf,.ppt,.pptx"
              >
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
            <el-form-item label="审核结果：" v-if="examining">
              <el-radio-group v-model="formLabelAlign.examineType">
                <el-radio :label="2">通过</el-radio>
                <el-radio :label="3">不通过</el-radio>
                <el-radio :label="4" v-show="finalCheck == 1">存疑</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="审核意见：" v-if="examining">
              <el-select
                v-model="expertMemoItems"
                multiple
                collapse-tags
                @change="expertMemoChange"
                placeholder="请选择">
                <el-option
                  v-for="(item,index) in expertMemoOptions"
                  :key="index"
                  :label="item.memo"
                  :value="index">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="审核意见：" v-if="examining">
              <el-input type="textarea" :rows="3" placeholder="请输入审核意见" v-model="formLabelAlign.expertMemo"/>
            </el-form-item>
          </div>
        </div>  
      </el-form>
      <div class="upload"></div>
      <div class="footer flex-center">
        <div class="cancel" @click="closeDialog">取消</div>
        <div class="confirm" @click="submitForm">确定</div>
      </div>
    </el-dialog>
    <el-dialog
      class="extract-doc"
      title="资料上传"
      :visible.sync="extractDialogVisible"
      @closed="progressClose"
    >
      <div class="top-progress flex-center">
        <div class="flex-center">
          <div class="tit">上传中</div>
          <el-progress :percentage="percentage" :format="format"></el-progress>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from "vuex";
import tagsGroup from "@/components/common/tagsGroup.vue";
export default {
  components: { tagsGroup },
  props: {
    title: {
      default: () => "新增", //是否编辑
    },
    formLabelAlign: {
      default: () => {
        return {
          fileName: "", //文件名
          memo: "", //描述
          id: "",
          keywords: "", //主题词
          fileList: [],
          examineType: 2,
          expertMemo: '',
        };
      },
    },
    checkedId: {
      default: () => [],
    },
    item: {
      default: () => {},
    },
  },
  data() {
    return {
      expertMemoOptions: [],
      expertMemoItems: [],
      percentage: 1,
      extractDialogVisible: false, // 进度条弹窗
      interval: 0,
      dialogVisible: false, // 模态框默认不显示
      uploadFileName: "", // 上传文件后文件所在列表
      fileList: [],
      labelPosition: "right", // 默认输入框前面的标题右居中显示
      showTagsArr: [], // 标签显示的id列表
      baseURL: `${window.VUE_APP_BASE_URL}/imageData/uploadDataFile`,
      // loading: null,
      treeTags: [],
      defaultProps: {
        children: "categoryTypeList",
        label: "name",
      },
      fatherIds: [],
      chekedIds: [], // 单选tree
      categoryIds: [],
      dataList: [],
      pageSize: 12,
      uploadOtherData: null
    };
  },
  computed: {
    ...mapState({
      targetTreeChecked(state) {
        return state.app.targetTreeChecked;
      },
      targetTreeSingleId(state) {
        return state.app.targetTreeSingleId;
      },
      user(state) {
        return state.user
      },
      examining(state) {
        return state.app.examining
      },
      finalCheck(state) {
        return state.app.finalCheck || 1
      }
    })
  },
  watch: {
    extractDialogVisible(n) {
      if (!n) {
        this.clearIntervalAll();
      }
    }
  },
  beforeDestroy() {
    this.$store.commit("app/setTargetTreeIsSingle", false);
  },
  created() {
    // 目标树改为单选
    this.$store.commit("app/setTargetTreeIsSingle", true);
    this.categoryAndGroup();
    this.getMemo();
  },
  methods: {
    expertMemoChange(value) {
      this.formLabelAlign.expertMemo = ''
      if (value.length > 0) {
        value.forEach(item => {
          this.formLabelAlign.expertMemo += this.expertMemoOptions[item].memo + ' || '
        })
      }
    },
    async getMemo(){
      this.expertMemoOptions = await this.$api.getMemo()
    },
    // 进度条
    setPercentage() {
      this.extractDialogVisible = true;
      this.percentage = 1;
      this.interval = setInterval(() => {
        if (this.percentage > 92) {
          this.percentage = 99;
        } else {
          this.percentage += 6 * Math.random();
          this.percentage = parseInt(this.percentage);
        }
      }, 300);
    },
    format(percentage) {
      return percentage === 100 ? "满" : `${percentage}%`;
    },
    clearIntervalAll() {
      clearInterval(this.interval);
    },
    progressClose() {
      this.percentage = 1;
    },
    // 打开模态框的回调   父组件通过子组件的这个方法打开模态框
    openDialog() {
      this.dialogVisible = true;
      if (this.title === "新增") {
        this.fileList = [];
      }
    },
    open() {
      if (this.title === "编辑" || this.title === "审核") {
        this.categoryIds = this.item.categoryTypeList.map((key) => {
          return key.id;
        });
        this.$nextTick(() => {
          this.$refs.elTree.setCheckedKeys(this.categoryIds);
        });
        this.fileList = this.formLabelAlign.fileList;
      }
    },
    closeDialog() {
      this.$emit("closeDialog", this.dialogVisible);
      //this.checkedId = [];
      this.setChecedId([])
      this.categoryIds = [];
      this.$refs.elTree.setCheckedKeys([]);
      this.fileList = [{ name: "", url: "", response: "" }];
      // this.formLabelAlign = {
      //  fileName: "", //文件名
      //  memo: "", //描述
      //  id: "",
      // keywords: "", //主题词
      //  fileList: [],
      //  examineType: 2,
      //  expertMemo: '',
      //};
      this.$emit("setObj",{
          fileName: "",
          memo: "",
          id: "",
          keywords: "", //主题词
          fileList: []
      })
      this.dialogVisible = false
    },
    // 查询标签组及其下标签
    async categoryAndGroup() {
      this.treeTags = await this.$api.categoryAndGroup();
      this.treeTags.forEach((item) => {
        item.categoryTypeList.forEach((key) => {
          key.disabled = false;
        });
      });
    },
    // 移除上传错误的文件
    handleRemove(file) {
      this.fileList.pop(file);
    },
    // 文件上传失败时的钩子
    handleError(err, file, fileList) {
      console.log(err, file, fileList)
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePreview(file) {
      console.log(file, this.fileList);
    },
    handleSuccess(data, file, fileList) {
      // console.log('handleSuccess', data.indexOf('200'), data, file, fileList)
      if (data.indexOf('500') != -1) {
        this.$message({
          type: 'error',
          message: data.split(',')[1],
          showClose: true
        })
        this.handleRemove(file)
        return;
      }
      this.fileList = fileList.slice(-1);
      if (!this.formLabelAlign.fileName) {
        this.formLabelAlign.fileName = file.raw.name;
      }
      this.uploadFileName = file.raw.name;
    },
    // 上传文件之前的钩子，参数为上传的文件，若返回 false 或者返回 Promise 且被 reject，则停止上传。
    beforeUpload(file) {
      console.log(file.type);
      const fileType = file.type;
      if (fileType.indexOf('application/') == -1) {
        console.log('xxx')
        this.$message({
          message: "上传资料只能是 word 格式、ppt格式、pdf格式！",
          type: "warning",
          showClose: true
        });
        return false;
      }
      const sizeLimit = file.size / 1024 / 1024 / 1024 < 1; //这里做文件大小限制 1GB!
      if (!sizeLimit) {
        this.$message({
          message: "上传文件大小不能超过 1GB!",
          type: "warning",
          showClose: true
        });
        return false;
      }
      /* this.loading = this.$loading({
        lock: true,
        text: "努力上传中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      }); */
      let isJPG =
        file.name.split(".").pop().toLowerCase() === "word" ||
        file.name.split(".").pop().toLowerCase() === "wps" ||
        file.name.split(".").pop().toLowerCase() === "doc" ||
        file.name.split(".").pop().toLowerCase() === "docx" ||
        file.name.split(".").pop().toLowerCase() === "ppt" ||
        file.name.split(".").pop().toLowerCase() === "pptx" ||
        file.name.split(".").pop().toLowerCase() === "pdf";
      if (!isJPG) {
        // this.$message.error("上传资料只能是 word 格式、ppt格式、pdf格式！");
        this.$message({
          type: 'warning',
          message: '上传资料只能是 word 格式、ppt格式、pdf格式！',
          showClose: true
        })
        // this.loading.close();
        return false;
      }
      return true;
    },
    // 关闭模态框之前
    beforeClose() {
      //this.checkedId = [];
      this.setChecedId([])
      this.fileList = [{ name: "", url: "", response: "" }];
    },
    setChecedId(data){
        this.$emit("setCheckedId", data);
    },
    getNowTime() {
      let nowDate = new Date();
      let date = {
        year: nowDate.getFullYear(),
        month: nowDate.getMonth() + 1,
        date: nowDate.getDate(),
        Hour: nowDate.getHours(),
        Minute: nowDate.getMinutes(),
        Second: nowDate.getSeconds(),
      };
      let dataTime = `${date.year}/${date.month}/${date.date} ${date.Hour}:${date.Minute}:${date.Second}`;
      return dataTime
    },
    // 模态框确认
    submitForm() {
      console.log('submitForm', this.title, this.fileList);
      if (this.title == "新增" && this.fileList.length == 0) {
        this.$message({
          type: "warning",
          message: "请先上传文件",
          showClose: true
        });
        return;
      }
      const dataTime = this.getNowTime();
      if (this.title == "新增") {
        // 新增
        let data = {
          categoryIds: this.categoryIds,
          classificationId: 1,
          dataDate: dataTime,
          importanceId: 1,
          isProduct: 1,
          isExamine: 1,
          fileName: this.formLabelAlign.fileName,
          memo: this.formLabelAlign.memo,
          operator: this.user.loginName || '游客',
          themeWord: this.formLabelAlign.keywords,
          realFileUrl: this.fileList.length > 0 ? this.fileList[0].response : "",
          uploadFileName: this.uploadFileName,
        };
        this.setPercentage();
        this.$api.addDataInfo(data).then(() => {
          this.extractDialogVisible = false;
          this.dialogVisible = false;
          this.$emit("reGetData");
          this.$message({
            type: "success",
            message: "添加成功!",
            showClose: true
          });
          this.closeDialog()
        });
      } else if (this.title == "编辑") {
        // 编辑
        let editData = {
          categoryIds: this.categoryIds,
          classificationId: 1,
          importanceId: 1,
          dataDate: dataTime,
          isExamine: 1,
          isProduct: 1,
          id: this.formLabelAlign.id,
          fileName: this.formLabelAlign.fileName,
          memo: this.formLabelAlign.memo,
          operator: this.user.loginName || '游客',
          themeWord: this.formLabelAlign.keywords,
          realFileUrl: this.fileList.length > 0 ? this.fileList[0].response : "",
          uploadFileName: this.uploadFileName,
        };
        this.setPercentage();
        this.$api.updateDataInfo(editData).then(() => {
          this.extractDialogVisible = false;
          this.dialogVisible = false;
          this.$emit("reGetData");
          this.$message({
            type: "success",
            message: "编辑成功!",
            showClose: true
          });
          this.closeDialog()
        });
      } else if (this.title == "审核") {
        // 审核
        let syncData = {
          categoryIds: this.categoryIds,
          classificationId: 1,
          importanceId: 1,
          dataDate: dataTime,
          isExamine: 1,
          isProduct: 1,
          id: this.formLabelAlign.id,
          ids: [this.formLabelAlign.id.toString()],
          fileName: this.formLabelAlign.fileName,
          memo: this.formLabelAlign.memo,
          operator: this.user.loginName || "游客",
          themeWord: this.formLabelAlign.keywords,
          realFileUrl: this.fileList.length > 0 ? this.fileList[0].response : "",
          uploadFileName: this.uploadFileName,
          examineType: this.formLabelAlign.examineType,
          expertMemo: this.formLabelAlign.expertMemo,
          finalCheck: this.finalCheck,
        };
        
        this.setPercentage();
        this.$api.examineDataInfo(syncData).then(() => {
          this.extractDialogVisible = false;
          this.$emit("reGetData");
          this.$message({
            type: "success",
            message: "审核成功!",
            showClose: true
          });
          // 重新获取数据
          this.closeDialog()
        });
      }
      
    },
    handleNodeClick(data, checked) {
        console.log(data, checked)
      if (checked) {
        this.treeTags.forEach((item) => {
          item.categoryTypeList.forEach((key) => {
            if (key.id == data.id) {
              this.fatherIds.push(item.id);
              this.chekedIds.push({
                father: item.id,
                son: key.id,
              });
            }
          });
        });
      }
    },
    treeCheck(data, checked) {
      let that = this;
      let categoryArr = [];
      if (checked.checkedKeys.length >= 1) {
        this.treeTags.forEach((item) => {
          item.categoryTypeList.forEach((key) => {
            if (key.id == data.id) {
              if (that.fatherIds.indexOf(item.id) !== -1) {
                that.chekedIds = that.chekedIds.filter(
                  (j) => j.father != item.id
                );
                that.chekedIds.push({
                  father: item.id,
                  son: key.id,
                });
                categoryArr = that.chekedIds.map((k) => {
                  return k.son;
                });
                that.$nextTick(() => {
                  that.$refs.elTree.setCheckedKeys(categoryArr);
                })
              }
            }
          });
        });
      }
      this.categoryIds = categoryArr;
    },
    tagsDel(e) {
      this.categoryIds = this.categoryIds.filter((item) => item != e);
      this.chekedIds = this.chekedIds.filter((i) => i.son != e);
      this.$nextTick(() => {
        this.$refs.elTree.setCheckedKeys(this.categoryIds);
      })
      this.$api.getTag(e).then((res) => {
        this.fatherIds = this.fatherIds.filter((item) => item != res.groupId);
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";
::v-deep .el-dialog {
  color: #ffffff;
  font-size: 0.16rem;
  width: 10rem;
  // background: #474747;
  box-shadow: 0px 0px 38px 0px rgba(0, 0, 0, 0.45);
  border-radius: 0.05rem;
  .el-dialog__header {
    padding: 0.16rem;
    background: #143853 !important;
  }
  .el-dialog__title {
    color: #ffffff;
  }
  .el-dialog__body {
    color: #ffffff;
    background: #0f2d43 !important;
  }
  .el-form-item__label {
    color: #ffffff;
  }
  .el-input__inner {
    background: #0355a4 !important;
    border: none;
  }
  .el-textarea__inner {
    height: 1rem;
    background: #144f87;
    border: 1px solid #0355a4;
    border-radius: 0.05rem;
    color: #ffffff;
  }
  .el-input__count {
    background: #144f87;
    border: none;
  }
  input {
    color: #ffffff;
  }
  input::-webkit-input-placeholder {
    color: #ffffff;
  }
  input::-moz-input-placeholder {
    color: #ffffff;
  }
  input::-ms-input-placeholder {
    color: #ffffff;
  }
  .el-select {
    color: #ffffff;
    width: 100%;
    background: #0355a4;
    .el-input__inner {
      background: #0355a4;
    }
  }
  .footer {
    margin-top: 0.3rem;
    color: #ffffff;
    margin-right: 0.3rem;
    justify-content: flex-end;
    .cancel {
      text-align: center;
      width: 1.2rem;
      height: 0.38rem;
      line-height: 0.38rem;
      background: #62656c;
      border-radius: 0.05rem;
    }
    .confirm {
      margin-left: 0.2rem;
      text-align: center;
      width: 1.2rem;
      height: 0.38rem;
      line-height: 0.38rem;
      background: #1890ff;
      border-radius: 0.05rem;
    }
  }
}
.tag {
  padding: 0.08rem;
  height: 0.98rem;
  width: 100%;
  background: #0355a4;
  border-radius: 0.05rem;
  margin-bottom: 0.06rem;
  overflow-y: auto;
}

.navUpload {
  display: flex;
  justify-content: space-between;
  .nav {
    width: 50%;
    ::v-deep .el-tree {
      @include scrollBar;
      overflow-y: auto;
      width: 100%;
      height: 2.98rem;
      background: #0355a4;
      border-radius: 0rem 0rem 0.05rem 0.05rem;
      color: #cccccc;
      .el-tree-node:focus > .el-tree-node__content {
        background: #034576; //背景色
      }
      .el-tree-node__content {
        height: 0.3rem;
        &:hover {
          background: #034576;
        }
      }
      .el-tree-node__label {
        font-size: 0.16rem;
        color: #cccccc;
        line-height: 0.25rem;
        letter-spacing: 1px;
      }
    }
  }
  .upload {
    width: 50%;
    display: flex;
    flex-direction: column;
    position: relative;
    .el-from-item {
      width: 70%;
    }
    ::v-deep .el-upload-list__item-name {
      width: 3rem;
      color: #ffffff;
      font-size: 0.18rem;
      .el-upload-list__item-name:hover {
        color: #1682e6 !important;
      }
    }
    ::v-deep.el-upload-list__item-name:hover {
      color: #1682e6 !important;
    }
  }
}
// 标签
.target-tree-con {
  width: 100%;
  .input {
    overflow-y: auto;
    @include scrollBar;
    margin-bottom: 0.1rem;
    min-height: 0.4rem;
    max-height: 1rem;
    line-height: 0.4rem;
    outline: none;
    padding: 0 0.15rem;
    transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
    font-size: 0.14rem;
    background: #0355a4 !important;
    border: 1px solid #0355a4;
    border-radius: 0.05rem;
    color: #ffffff;
  }
}
.treeTags {
  width: 100%;
  ::v-deep .el-tree {
    overflow-y: auto;
    @include scrollBar;
    width: 100%;
    height: 2.98rem;
    background: rgba(83, 83, 83, 0.7);
    border-radius: 0rem 0rem 0.05rem 0.05rem;
    color: #cccccc;
    // margin-top: 0.1rem;
    // background: transparent;
    .el-tree-node:focus > .el-tree-node__content {
      background-color: #2f2f2f; //背景色
    }
    .el-tree-node__content {
      height: 0.3rem;
      &:hover {
        background: #2f2f2f;
      }
    }
    .el-tree-node__label {
      font-size: 0.16rem;
      color: #cccccc;
      line-height: 0.25rem;
      letter-spacing: 1px;
    }
    .el-tree-node__expand-icon + label {
      // display: none;
    }
    .is-leaf + .el-checkbox .el-checkbox__inner {
      display: inline-block;
    }
    .el-checkbox .el-checkbox__inner {
      display: none;
    }
  }
}
::v-deep .extract-doc {
  .el-dialog {
    color: #ffffff;
    font-size: 0.16rem;
    width: 9.56rem !important;
    background: #474747;
    box-shadow: 0rem 0rem 0.38rem 0rem rgba(0, 0, 0, 0.45);
    border-radius: 0.05rem;
    .el-dialog__header {
      padding: 0.16rem;
      background: #143853 !important;
    }
    .el-dialog__title {
      color: #ffffff;
    }
    .el-dialog__body {
      color: #ffffff;
      background: #0f2d43 !important;
    }
    .top-progress {
      .el-progress {
        width: 7.5rem;
        margin-left: 0.08rem;
        .el-progress__text {
          color: #fff;
        }
      }
      .pause {
        width: 0.94rem;
        height: 0.28rem;
        background: #1890ff;
        border-radius: 0.05rem;
        .icon {
          margin-right: 0.06rem;
          width: 0.09rem;
          height: 0.14rem;
          background-image: url(~@/assets/common/extract@2x.png);
          background-repeat: no-repeat;
          background-size: 100% 100%;
          background-position: center;
        }
      }
      .begin {
        margin-left: 0.1rem;
        width: 0.94rem;
        height: 0.28rem;
        background: #62656c;
        border-radius: 0.05rem;
        .icon {
          margin-right: 0.06rem;
          width: 0.09rem;
          height: 0.14rem;
          background-image: url(~@/assets/common/extract@2x.png);
          background-repeat: no-repeat;
          background-size: 100% 100%;
          background-position: center;
        }
      }
    }
    .footer {
      margin-top: 0.3rem;
      color: #ffffff;
      margin-right: 0.3rem;
      justify-content: flex-end;
      .cancel {
        text-align: center;
        width: 1.2rem;
        height: 0.38rem;
        line-height: 0.38rem;
        background: #62656c;
        border-radius: 0.05rem;
      }
      .confirm {
        margin-left: 0.2rem;
        text-align: center;
        width: 1.2rem;
        height: 0.38rem;
        line-height: 0.38rem;
        background: #1890ff;
        border-radius: 0.05rem;
      }
    }
  }
}
</style>
